import { createApp, ref, computed, onMounted } from 'vue'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import { storage } from './utils/storage.js'
import { exportToExcel } from './utils/excel.js'
import { generateOrderNumber, calculateTotal as calcTotal } from './utils/format.js'
import { ElMessage, ElMessageBox } from 'element-plus'
import './styles/main.css'

const app = createApp({
  setup() {
    const orders = ref([])
    const loading = ref(true)
    const dialogVisible = ref(false)
    const dialogTitle = ref('新增订单')
    const orderFormRef = ref(null)
    const editingOrderId = ref(null)

    const orderForm = ref({
      orderDate: '',
      orderNumber: '',
      style: '',
      size: '',
      quantity: 1,
      unitPrice: 0
    })

    const formRules = {
      orderDate: [{ required: true, message: '请选择下单日期', trigger: 'change' }],
      orderNumber: [{ required: true, message: '请输入单号', trigger: 'blur' }],
      style: [{ required: true, message: '请输入款式', trigger: 'blur' }],
      size: [{ required: true, message: '请输入尺寸', trigger: 'blur' }],
      quantity: [{ required: true, message: '请输入数量', trigger: 'blur' }],
      unitPrice: [{ required: true, message: '请输入单价', trigger: 'blur' }]
    }

    // 计算总额
    const totalAmount = computed(() => {
      return calcTotal(orderForm.value.quantity, orderForm.value.unitPrice).toFixed(2)
    })

    // 加载订单
    const loadOrders = () => {
      try {
        orders.value = storage.getOrders()
        console.log('Loaded orders:', orders.value)
      } catch (error) {
        console.error('Error loading orders:', error)
        ElMessage.error('加载订单失败')
      } finally {
        loading.value = false
      }
    }

    // 显示新增对话框
    const showAddDialog = () => {
      dialogTitle.value = '新增订单'
      editingOrderId.value = null
      orderForm.value = {
        orderDate: new Date().toISOString().split('T')[0],
        orderNumber: generateOrderNumber(),
        style: '',
        size: '',
        quantity: 1,
        unitPrice: 0
      }
      dialogVisible.value = true
    }

    // 编辑订单
    const editOrder = (order) => {
      dialogTitle.value = '编辑订单'
      editingOrderId.value = order.id
      orderForm.value = {
        orderDate: order.orderDate,
        orderNumber: order.orderNumber,
        style: order.style,
        size: order.size,
        quantity: order.quantity,
        unitPrice: order.unitPrice
      }
      dialogVisible.value = true
    }

    // 提交订单
    const submitOrder = async () => {
      if (!orderFormRef.value) return

      await orderFormRef.value.validate((valid) => {
        if (valid) {
          try {
            if (editingOrderId.value) {
              // 更新订单
              storage.updateOrder(editingOrderId.value, orderForm.value)
              ElMessage.success('订单更新成功')
            } else {
              // 新增订单
              storage.addOrder(orderForm.value)
              ElMessage.success('订单添加成功')
            }
            dialogVisible.value = false
            loadOrders()
          } catch (error) {
            console.error('Submit error:', error)
            ElMessage.error('操作失败')
          }
        }
      })
    }

    // 删除订单
    const deleteOrder = async (id) => {
      try {
        await ElMessageBox.confirm('确定要删除这条订单吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        storage.deleteOrder(id)
        ElMessage.success('删除成功')
        loadOrders()
      } catch {
        // 用户取消删除
      }
    }

    // 导出Excel
    const exportOrders = () => {
      if (orders.value.length === 0) {
        ElMessage.warning('暂无数据可导出')
        return
      }
      try {
        exportToExcel(orders.value, '家具订单_后端')
        ElMessage.success('导出成功')
      } catch (error) {
        console.error('Export error:', error)
        ElMessage.error('导出失败')
      }
    }

    // 生成订单号
    const generateNumber = () => {
      orderForm.value.orderNumber = generateOrderNumber()
    }

    // 计算总额
    const calculateTotal = () => {
      // 自动计算在computed中完成
    }

    onMounted(() => {
      console.log('Admin app mounted')
      try {
        storage.initSampleData()
        loadOrders()
      } catch (error) {
        console.error('Mount error:', error)
        loading.value = false
      }
    })

    return {
      orders,
      loading,
      dialogVisible,
      dialogTitle,
      orderForm,
      orderFormRef,
      formRules,
      totalAmount,
      showAddDialog,
      editOrder,
      submitOrder,
      deleteOrder,
      exportOrders,
      generateNumber,
      calculateTotal
    }
  }
})

app.use(ElementPlus)

try {
  app.mount('#app')
  console.log('Admin app initialized successfully')
} catch (error) {
  console.error('Mount failed:', error)
}
